class RatingController < ApplicationController
  
  def rate
    if logged_in?
      @story = Story.find(params[:id])
      Rating.delete_all(["rateable_type = 'Story' AND rateable_id = ? AND user_id = ?", 
        @story.id, current_user.id])
      @story.add_rating Rating.new(:rating => params[:rating], 
        :user_id => current_user.id)
      set_ratings
      @story.save
    end
  end
  
  protected
  
  def set_ratings
    ratings = @story.ratings
    @story.rating = ratings.inject(0) {|sum, r| sum + r.rating} / ratings.length
  end

end
